let titles = []; // 存储题目数据
let cuoti = []; // 存储错题数据
const app = getApp();

// 用于记录答题开始时间
let startTime;
// 用于记录总时间（以秒为单位）
let totalTime = 0;
// 用于定时器的标识，方便后续清除定时器
let timer;

// 定义计算得分的函数
function calculateScore(userAnswer, correctAnswer) {
  return userAnswer === correctAnswer ? 1 : 0;
}

// 定义统计错题的函数
function collectCuoti(userAnswer, correctAnswer) {
  return userAnswer !== correctAnswer;
}

Page({
  data: {
    total: 0,
    isSelect: false,
    subject: null,
    userSelect: '',
    userScore: 0,
    totalScore: -1,
    totalError: 0,
    current: 1,
    correctAnswer: '',
    explain: '',
    hasAnsweredFirstQuestion: false,
    showFinishButton: false,
    answered: [], 
    correctCount: 0, 
    totalTime: 0 
  },

  onLoad() {
    wx.cloud.database().collection('timu')
      .where({
        type: "判断"
      })
      .get()
      .then(res => {
        console.log('题库数据', res);
        let allTitles = res.data;

        // 随机选择10道题目
        let shuffledTitles = allTitles.sort(() => Math.random() - 0.5);
        titles = shuffledTitles.slice(0, 10);

        titles.forEach((item, index) => {
          item.serialNumber = index + 1;
        });

        this.setData({
          subject: titles[0],
          total: titles.length,
          answered: new Array(titles.length).fill(false), 
          correctCount: 0, // 初始化答对题目数量
          totalTime: 0 // 初始化总时间
        });
        startTime = Date.now();
        this.startTimer(); // 启动定时器，开始记录答题时间
      });
  },

  startTimer() {
    timer = setInterval(() => {
      let currentTime = Math.floor((Date.now() - startTime) / 1000);
      this.setData({
        totalTime: currentTime
      });
    }, 1000);
  },

  optionChange(e) {
    let value = e.detail.value;
    this.setData({
      userSelect: value
    });
  },

  // 提交答案按钮点击事件处理函数
  submitAnswer() {
    let currentNum = this.data.current - 1;
    if (!this.data.userSelect) {
      wx.showToast({
        icon: 'none',
        title: '请选择答案',
      });
      return;
    }

    this.setData({
      answered: this.data.answered.map((v, index) => index === currentNum ? true : v)
    });

    let that = this;
    wx.cloud.database().collection('timu').where({
      type: "判断",
      _id: this.data.subject._id
    }).get().then(res => {
      if (res.data.length > 0) {
        let explainData = res.data[0].explain;
        let correctAnswer = res.data[0].answer;
        that.setData({
          correctAnswer,
          explain: explainData
        });

        let options = that.data.subject.options;
        for (let i = 0; i < options.length; i++) {
          if (options[i].code === that.data.userSelect) {
            options[i].color = that.data.userSelect === correctAnswer ? '#32CD32' : 'red';
          } else {
            options[i].color = 'black'; // 用户未选择的选项，无论对错，都设置为黑色
          }
        }

        that.setData({
          subject: {
            ...that.data.subject,
            options
          }
        });

        // 统计分数
        let score = calculateScore(that.data.userSelect, correctAnswer);
        that.setData({
          userScore: that.data.userScore + score,
          totalScore: that.data.userScore + score
        });

        // 更新答对题目数量
        if (score === 1) {
          that.setData({
            correctCount: that.data.correctCount + 1
          });
        }

        // 统计错题
        if (collectCuoti(that.data.userSelect, correctAnswer)) {
          cuoti.push(titles[currentNum]);
          that.saveCuotiToDatabase(res.data[0], that.data.userSelect);
        }

        if (currentNum === titles.length - 1) {
          that.setData({
            totalScore: that.data.userScore,
            totalError: cuoti.length,
            showFinishButton: true
          });
        }
      }
    });
  },

  saveCuotiToDatabase(questionData, userAnswer) {
    const openid = wx.getStorageSync('openid');
    const db = wx.cloud.database();
    const usersCollection = db.collection('users');

    usersCollection.where({
      openid: openid
    }).get().then(res => {
      if (res.data.length > 0) {
        let cuoti = res.data[0].cuoti || [];
        let existingQuestion = cuoti.find(item => item.title === questionData.title);
        if (existingQuestion) {
          console.log('已存在相同标题的记录', existingQuestion);
          wx.showToast({
            title: '此题目已记录为错题',
            icon: 'none'
          });
        } else {
          cuoti.push({
            questionId: questionData._id,
            title: questionData.title,
            options: this.data.subject.options,
            userAnswer: userAnswer,
            correctAnswer: questionData.answer,
            type: questionData.type,
            explain: questionData.explain,
            timestamp: new Date().toISOString()
          });
          usersCollection.doc(res.data[0]._id).update({
            data: {
              cuoti: cuoti
            },
            success: res => {
              console.log('错题已成功保存到用户记录', res);
              wx.showToast({
                title: '错题记录成功',
                icon: 'success'
              });
            },
            fail: err => {
              console.error('保存错题失败', err);
              wx.showToast({
                title: '错题记录失败',
                icon: 'none'
              });
            }
          });
        }
      } else {
        console.error('用户记录不存在');
        wx.showToast({
          title: '用户记录不存在',
          icon: 'none'
        });
      }
    }).catch(err => {
      console.error('查询用户记录失败', err);
    });
  },

  seeError() {
    console.log('查看错题');
    wx.setStorageSync('xiao', cuoti);
    wx.navigateTo({
      url: '/pages/cuoti/cuoti',
    });
  },

  prevQuestion() {
    let currentNum = this.data.current;
    if (currentNum > 1) {
      currentNum--;
      let subject = titles[currentNum - 1];

      this.setData({
        current: currentNum,
        subject,
        userSelect: this.data.answered[currentNum - 1] ? this.data.userSelect : '', // 如果已回答过，则保留上次的选择
        isSelect: this.data.answered[currentNum - 1],
        correctAnswer: subject.answer,
        explain: subject.explain
      });
    } else {
      wx.showToast({
        icon: 'none',
        title: '已经是第一题了',
      });
    }
  },

  nextQuestion() {
    let currentNum = this.data.current;
    if (currentNum < titles.length) {
      if (!this.data.userSelect && !this.data.answered[currentNum - 1]) {
        wx.showToast({
          icon: 'none',
          title: '请先选择答案并提交，再进入下一题',
        });
        return;
      }
      currentNum++;
      let subject = titles[currentNum - 1];
      this.setData({
        current: currentNum,
        subject
      }, () => {
        if (this.data.answered[currentNum - 1]) {
          let that = this;
          wx.cloud.database().collection('timu').where({
            type: "判断",
            _id: subject._id
          }).get().then(res => {
            if (res.data.length > 0) {
              let explainData = res.data[0].explain;
              let correctAnswer = res.data[0].answer;
              that.setData({
                correctAnswer,
                explain: explainData
              });
            }
          });
        } else {
          this.setData({
            correctAnswer: '',
            explain: ''
          });
        }
        this.setData({
          userSelect: '',
          isSelect: false
        });
      });
    } else {
      wx.showToast({
        icon: 'static',
        title: '已经是最后一题了',
      });
    }
  },

  goToFinishPage() {
    if (timer) {
      clearInterval(timer);
      console.log('准备传递给answer-finish页面的答题总时间和答对题目数量：', this.data.totalTime, this.data.correctCount);
      wx.redirectTo({
        url: `/pages/answer-finish/answer-finish?totalTime=${this.data.totalTime}&correctCount=${this.data.correctCount}`,
      });
    }
  },

  // 收藏题目
  collectQuestion() {
    const questionData = {
      questionId: this.data.current,
      title: this.data.subject.title,
      options: this.data.subject.options,
      userAnswer: this.data.userSelect,
      correctAnswer: this.data.subject.answer,
      type: this.data.subject.type,
      explain: this.data.subject.explain,
      timestamp: new Date().toISOString() 
    };

    const openid = wx.getStorageSync('openid');
    const db = wx.cloud.database();
    const usersCollection = db.collection('users');

    usersCollection.where({
      openid: openid
    }).get().then(res => {
      let save = res.data[0].save || [];
      let existingQuestion = save.find(item => item.title === questionData.title);
      if (existingQuestion) {
        console.log('已存在相同标题的记录', existingQuestion);
        wx.showToast({
          title: '此题目已收藏',
          icon: 'none'
        });
      } else {
        save.push(questionData);
        usersCollection.doc(res.data[0]._id).update({
          data: {
            save: db.command.push(save)
          },
          success: res => {
            console.log('题目已成功保存到用户记录', res);
            wx.showToast({
              title: '收藏成功',
              icon: 'success'
            });
          },
          fail: err => {
            console.error('保存题目失败', err);
            wx.showToast({
              title: '收藏失败',
              icon: 'none'
            });
          }
        });
      }
    }).catch(err => {
      console.error('查询用户记录失败', err);
    });
  }
});